<!--
 * Copyright © 2022 XXXXXXXXX
 * @Author: zhangxiang
 * @Date: 2022-08-04 18:01:36
 * @LastEditors: zhangxiang
 * @LastEditTime: 2023-09-21 15:08:09
 * @Description:
 *
-->

<template>
  <div class="workload-mgmt-ctn">
    <el-row type="flex" style="margin-bottom: 20px">
      <el-input
        v-model="searchKey"
        style="width: 200px; margin-right: 20px"
        size="small"
        class="input"
        placeholder="请输入关键字进行过滤"
        clearable
        @clear="clearClick"
        @keyup.enter.native="queryClick"
      />
      <el-button
        size="small"
        type="primary"
        @click="queryClick"
      >查询</el-button>
      <el-tag
        v-if="svcName"
        style="margin-left: 20px"
        closable
        @close="svcCloseClick"
      >
        {{ svcName }}
      </el-tag>
      <el-button
        size="small"
        type="primary"
        style="margin-left: auto"
        icon="el-icon-plus"
        @click="createClick"
      >创建工作负载</el-button>
    </el-row>
    <el-table
      key="workload"
      v-loading="loading"
      class="workload-table"
      :data="list"
      header-cell-class-name="listHeaderCell"
      :header-cell-style="{ background: '#F3F3F3', color: '#696969' }"
      border
    >
      <el-table-column
        prop="cloudVendor"
        label="云商名称"
        min-width="110"
        show-overflow-tooltip=""
      >
        <template slot-scope="scope">
          {{ cloudVendorToChn(scope.row.cloudVendor) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="k8sClusterName"
        label="集群名称"
        min-width="170"
        show-overflow-tooltip=""
      />
      <el-table-column
        prop="workLoadName"
        label="负载名称"
        min-width="130"
        show-overflow-tooltip=""
      />
      <el-table-column
        prop="svcName"
        label="微服务名称"
        min-width="140"
        show-overflow-tooltip=""
      />
      <el-table-column prop="status" label="运行状态" width="110" />
      <el-table-column
        prop="namespace"
        label="命名空间"
        min-width="130"
        show-overflow-tooltip=""
      />
      <el-table-column prop="podNum" label="Pods数量" width="110">
        <template slot-scope="scope">
          <span>{{ scope.row.podNum }}/{{ scope.row.replicas }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTimeStr" label="创建时间" width="170" />
      <el-table-column label="操作" width="220" fixed="right">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            style="height: 22px; line-height: 22px; padding: 0 10px"
            @click="podsClick(scope.row)"
          >容器组列表</el-button>
          <el-button
            type="primary"
            size="mini"
            style="height: 22px; line-height: 22px; padding: 0 10px"
            @click="editClick(scope.$index)"
          >编辑</el-button>
          <el-popover
            :ref="`popover-delete-${scope.$index}`"
            placement="top"
            width="300"
            style="margin-left: 10px"
          >
            <p>是否确认删除该工作负载？</p>
            <div style="text-align: right; margin: 0">
              <el-button
                size="mini"
                type="text"
                @click="
                  scope._self.$refs[`popover-delete-${scope.$index}`].doClose()
                "
              >取消</el-button>
              <el-button
                type="primary"
                size="mini"
                @click="deleteClick(scope)"
              >确定</el-button>
            </div>
            <el-button
              slot="reference"
              type="danger"
              style="height: 22px; line-height: 22px; padding: 0 10px"
              size="mini"
            >删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <el-row type="flex" justify="end" style="margin-top: 25px">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next"
        :page-sizes="[10, 15, 20]"
        :page-size="pageSize"
        :current-page.sync="pageNum"
        :total="totalNum"
        @current-change="changePage"
        @size-change="sizeChange"
      />
    </el-row>

    <el-dialog
      class="workload-create-dialog"
      title="创建工作负载"
      :visible="showCreateDialog"
      width="800px"
      top="13vh"
      :close-on-click-modal="false"
      @close="showCreateDialog = false"
    >
      <div class="title-wrapper">
        <div class="title">按yaml文件创建</div>
      </div>
      <yaml-editor
        v-model="createYaml"
        class="create-yaml-wrapper"
        :height="'50vh'"
      />
      <div slot="footer" class="dialog-footer">
        <el-button
          size="small"
          @click="showCreateDialog = false"
        >取 消</el-button>
        <el-button
          type="primary"
          size="small"
          :loading="createConfirmLoading"
          :disabled="!createYaml"
          @click="createConfirmClick"
        >确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      class="workload-edit-dialog"
      title="编辑工作负载"
      :visible="showEditDialog"
      width="800px"
      top="15vh"
      append-to-body
      :close-on-click-modal="false"
      @close="showEditDialog = false"
    >
      <el-tabs v-model="editActiveName" type="card">
        <el-tab-pane label="扩缩容" name="tab1">
          <div class="wrapper1">
            <div class="text">设置目标副本数</div>
            <el-slider v-model="editReplicas" class="slider" :max="10" />
            <div class="text">{{ editReplicas }}个</div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="更新镜像" name="tab2">
          <el-form
            ref="imageForm"
            size="medium"
            :rules="editImageRules"
            :model="editImageForm"
            label-width="auto"
            style="margin: 30px 0"
          >
            <el-form-item label="容器名称" prop="containerName">
              <el-select
                v-model="editImageForm.containerName"
                placeholder="请选择容器"
                style="width: 100%"
              >
                <el-option
                  v-for="item in containerModels"
                  :key="item.containerName"
                  :label="item.containerName"
                  :value="item.containerName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="镜像地址" prop="containerImage">
              <el-input
                v-model="editImageForm.containerImage"
                placeholder="请输入镜像地址"
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="yaml文件更新" name="tab3" />
      </el-tabs>
      <yaml-editor
        v-if="editActiveName === 'tab3'"
        v-model="editYaml"
        class="edit-yaml-wrapper"
        :height="'50vh'"
      />
      <div slot="footer" class="dialog-footer">
        <el-button
          size="small"
          @click="showEditDialog = false"
        >取 消</el-button>
        <el-button
          type="primary"
          size="small"
          :loading="editConfirmLoading"
          @click="editConfirmClick"
        >确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import YamlEditor from '@/components/YamlEditor'
import {
  getK8sClusterWorkLoads,
  addK8sClusterWorkLoads,
  delK8sClusterWorkLoad,
  editK8sClusterWorkLoadContainers,
  editK8sClusterWorkLoadReplicas,
  editK8sClusterWorkLoadYaml
} from '@/api/cnap/hybrid-cloud'
import commonTab from '../mixin/commonTab'

export default {
  name: 'WorkLoadMgmt',
  components: {
    YamlEditor
  },
  mixins: [commonTab],
  data() {
    return {
      svcName: '', // 服务名
      showCreateDialog: false, // 展示创建弹窗
      createYaml: '', // 创建弹窗-yaml
      createConfirmLoading: false, // 创建弹窗-确定loading
      showEditDialog: false, // 展示编辑弹窗
      editActiveName: 'tab1', // 编辑-tab
      editIndex: 0, // 编辑-index
      editReplicas: 1, // 编辑-副本数
      editYaml: '', // 编辑-yaml
      containerModels: [], // 编辑-容器镜像
      // 校验规则
      editImageRules: {
        // 容器
        containerName: [
          { required: true, message: '请选择容器', trigger: 'blur' }
        ],
        // 镜像地址
        containerImage: [
          { required: true, message: '请输入镜像地址', trigger: 'blur' }
        ]
      },
      // 表单
      editImageForm: {
        containerName: '', // 容器
        containerImage: '' // 镜像
      },
      editConfirmLoading: false
    }
  },
  methods: {
    /**
     * @description: 创建 确定
     * @return {*}
     */
    createConfirmClick() {
      this.createConfirmLoading = true
      // 请求
      addK8sClusterWorkLoads({
        ...this.clusterParams,
        yaml: this.createYaml
      })
        .then((res) => {
          this.$message.success({
            message: '创建工作负载成功！',
            duration: '1500'
          })
          this.showCreateDialog = false // 关闭弹窗
          this.getWorkLoadInfos() // 刷新数据
        })
        .finally(() => {
          this.createConfirmLoading = false
        })
    },
    /**
     * @description: 创建
     * @return {*}
     */
    createClick() {
      this.createYaml = ''
      this.showCreateDialog = true // 显示创建弹窗
    },
    /**
     * @description: 编辑确定
     * @return {*}
     */
    editConfirmClick() {
      if (this.editActiveName === 'tab1') {
        // 扩缩容
        this.editConfirmLoading = true
        // 编辑请求
        editK8sClusterWorkLoadReplicas({
          ...this.clusterParams,
          namespace: this.list[this.editIndex].namespace,
          workLoadName: this.list[this.editIndex].workLoadName,
          workLoadKind: this.list[this.editIndex].workLoadKind,
          replicas: this.editReplicas
        })
          .then((res) => {
            this.$message.success({
              message: '扩缩容成功！',
              duration: '1500'
            })
            this.showEditDialog = false // 关闭弹窗
            this.getWorkLoadInfos() // 刷新数据
          })
          .finally(() => {
            this.editConfirmLoading = false
          })
      } else if (this.editActiveName === 'tab2') {
        // 更新镜像
        // 表单校验
        this.$refs.imageForm.validate((valid, obj) => {
          if (valid) {
            // 校验通过
            this.editConfirmLoading = true
            // 容器列表数据更新
            const idx = this.containerModels.findIndex((item) => {
              return item.containerName === this.editImageForm.containerName
            })
            this.containerModels[idx].containerImage =
              this.editImageForm.containerImage
            // 编辑请求
            editK8sClusterWorkLoadContainers({
              ...this.clusterParams,
              namespace: this.list[this.editIndex].namespace,
              workLoadName: this.list[this.editIndex].workLoadName,
              workLoadKind: this.list[this.editIndex].workLoadKind,
              containerModels: this.containerModels
            })
              .then((res) => {
                this.$message.success({
                  message: '更新镜像成功！',
                  duration: '1500'
                })
                this.showEditDialog = false // 关闭弹窗
                this.getWorkLoadInfos() // 刷新数据
              })
              .finally(() => {
                this.editConfirmLoading = false
              })
          }
        })
      } else if (this.editActiveName === 'tab3') {
        // yaml文件更新
        this.editConfirmLoading = true
        // 编辑请求
        editK8sClusterWorkLoadYaml({
          ...this.clusterParams,
          namespace: this.list[this.editIndex].namespace,
          workLoadName: this.list[this.editIndex].workLoadName,
          yaml: this.editYaml
        })
          .then((res) => {
            this.$message.success({
              message: '更新yaml文件成功！',
              duration: '1500'
            })
            this.showEditDialog = false // 关闭弹窗
            this.getWorkLoadInfos() // 刷新数据
          })
          .finally(() => {
            this.editConfirmLoading = false
          })
      }
    },
    /**
     * @description: 编辑
     * @param {*} index
     * @return {*}
     */
    editClick(index) {
      // 编辑弹窗相关数据保存
      this.editIndex = index
      this.editActiveName = 'tab1'
      this.editReplicas = this.list[index].replicas
      this.editYaml = this.list[index].yaml || ''
      if (this.$refs.imageForm) {
        this.$refs.imageForm.resetFields() // 表单重置
      }
      this.containerModels = this.list[index].containerModels || []
      this.showEditDialog = true
    },
    /**
     * @description: 容器组列表点击
     * @param {*} row
     * @return {*}
     */
    podsClick(row) {
      // 跳转路径
      const fullPath = `${this.$route.path}?cloudVendor=${row.cloudVendor}&accountName=${row.accountName || ''}&k8sClusterName=${row.k8sClusterName}&targetTab=pods&workLoadName=${row.workLoadName}&namespace=${row.namespace}`
      // 跳转容器组
      this.$router.replace({
        path: '/redirect' + fullPath
      })
    },
    /**
     * @description: 关闭服务标签
     * @return {*}
     */
    svcCloseClick() {
      this.svcName = ''
      this.pageNum = 1 // 第一页
      this.getWorkLoadInfos() // 请求数据
    },
    /**
     * @description: 删除
     * @param {*} scope
     * @return {*}
     */
    deleteClick(scope) {
      const row = scope.row
      // 删除请求
      delK8sClusterWorkLoad({
        ...this.clusterParams,
        namespace: row.namespace,
        workLoadName: row.workLoadName,
        workLoadKind: row.workLoadKind
      }).then((res) => {
        scope._self.$refs[`popover-delete-${scope.$index}`].doClose() // 关闭popover
        this.$message.success('删除成功')
        if (this.list.length === 1) {
          // 当前页只有一条数据时 删除完刷新上一页数据
          this.pageNum = Math.max(this.pageNum - 1, 1)
        }
        this.getWorkLoadInfos() // 刷新数据
      })
    },
    /**
     * @description: size变化
     * @param {*} size
     * @return {*}
     */
    sizeChange(size) {
      this.pageSize = size
      this.pageNum = 1
      this.getWorkLoadInfos() // 请求数据
    },
    /**
     * @description: 页码变化
     * @param {*} pageNum
     * @return {*}
     */
    changePage(pageNum) {
      this.pageNum = pageNum
      this.getWorkLoadInfos() // 请求数据
    },
    /**
     * @description: 清除关键字
     * @return {*}
     */
    clearClick() {
      this.searchKey = ''
      this.pageNum = 1
      this.getWorkLoadInfos() // 请求数据
    },
    /**
     * @description: 查询
     * @return {*}
     */
    queryClick() {
      this.pageNum = 1
      this.getWorkLoadInfos() // 请求数据
    },
    /**
     * @description: 获取工作负载列表
     * @return {*}
     */
    getWorkLoadInfos() {
      // 请求
      getK8sClusterWorkLoads({
        ...this.clusterParams,
        keyword: this.searchKey,
        svcName: this.svcName,
        pageNo: this.pageNum,
        pageSize: this.pageSize
      })
        .then((res) => {
          if (res.data) {
            this.totalNum = res.data.totalNum
            this.list = Array.isArray(res.data.result) ? res.data.result : []
          } else {
            // 数据为空处理
            this.totalNum = 0
            this.list = []
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    /**
     * @description: 初始化
     * @return {*}
     */
    initTabData() {
      if (this.$route.query.targetTab === 'workload') {
        // 目标Tab是workload时，获取参数中的svcName
        this.svcName = this.$route.query.svcName || '' // 服务名
        this.searchKey = this.$route.query.keyword || '' // 关键词
      }
      this.loading = true
      this.pageNum = 1
      this.getWorkLoadInfos() // 请求数据
    }
  }
}
</script>

<style lang="less" scoped>
@import "@/assets/css/common.less";
.workload-mgmt-ctn {
  .workload-table {
    /deep/ .el-table::before {
      background-color: #e9e9e9;
    }
    /deep/ .listHeaderCell {
      height: 40px;
      padding: 0;
      box-sizing: border-box;
      &:first-child {
        padding-left: 20px;
      }
    }
    /deep/ .el-table__body {
      .el-table__row td {
        height: 40px;
        padding: 0;
        &:first-child {
          padding-left: 20px;
        }
      }
    }
  }
  .workload-create-dialog {
    .title-wrapper {
      border-bottom: 1px solid #f2f2f2;
      margin-bottom: 12px;
      .title {
        box-sizing: border-box;
        display: inline-block;
        .textStyle(14px , 500, #0091ff);
        border-bottom: 2px solid #0091ff;
        padding: 4px 0;
      }
    }
  }
}
.workload-edit-dialog {
  .wrapper1 {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 50px 0 60px 0;
    .text {
      .textStyle(14px , 400, #4a4a4a);
      line-height: 20px;
    }
    .slider {
      flex: 1;
      margin: 0 10px;
      /deep/ .el-slider__runway {
        height: 10px;
        border-radius: 5px;
      }
      /deep/ .el-slider__bar {
        height: 10px;
        border-top-left-radius: 5px;
        border-bottom-left-radius: 5px;
      }
      /deep/ .el-slider__button-wrapper {
        top: -13px;
      }
    }
  }
}
</style>
